<?php
function getImage($url, $fileName, $saveDir = '') : array {
	$resArr = [
		'fileName' => '',
		'savePath' => '',
		'error' => '',
	];
	
	if('' == trim($url)) {
		$resArr['error'] = '文件不存在';
		return $resArr;
	}

	if('' == trim($fileName)) {
		$resArr['error'] = '文件名错误';
		return $resArr;
	}

	if('' == trim($saveDir)) {
		$saveDir = './';
	}
	if(mb_substr($saveDir, -1) != '/') {
		$saveDir .= '/';
	}
	
	if(!file_exists($saveDir) && !mkdir($saveDir)) {
		$resArr['error'] = '保存失败';
		return $resArr;
	}
	/*
	$ch=curl_init(); 
    curl_setopt($ch,CURLOPT_URL,$url); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5); 
    $img=curl_exec($ch); 
	curl_close($ch);
	*/
	//$img = getImageWithCurl($url);
	$img = getImageWithOb($url);
	if(empty($img)) {
		$resArr['error'] = '获取图片失败';
		return $resArr;
	}
	$fp = @fopen($saveDir . $fileName, 'a');
	fwrite($fp, $img);
	fclose($fp);
	unset($img,$url); 
	return [
		'fileName' => $fileName,
		'savePath' => $saveDir.$fileName,
		'error' => ''
	]; 

}

function getImageWithCurl($url) {
	$ch=curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
    $img=curl_exec($ch);
    curl_close($ch);
	return $img;
}


function getImageWithOb($url) {
	ob_start();
	readfile($url);
	$file = ob_get_contents();
	ob_end_clean();
	return $file;
}








?>
